package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWork {

    // 规定某天的时间戳
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    // 规定的序列号位数
    private static final long COUNT_BITS = 32L;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix){
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        // 当前时间的秒数
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        // 减去规定时间之差
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        // 生成序列化
        // 格式化今天的日期
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 拼接字符串，采用redis的increment递增方法，处理防止重复和并发的问题
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        return timestamp << COUNT_BITS | count;
    }

    public static void main(String[] args) {
        // 获取某一天的时间戳
        LocalDateTime time = LocalDateTime.of(2022,1,1,0,0,0);
        time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(time.toEpochSecond(ZoneOffset.UTC));
    }


}
